import {
	mapState
} from 'vuex'
import store from "@/store"
// 'import config from '@/common/config''

// 尝试将用户在根目录中的store/index.js的vuex的state变量，全部加载到全局变量中
let $uStoreKey = [];
try {
	$uStoreKey = store.state ? Object.keys(store.state) : [];
} catch (e) {

}

module.exports = {
	beforeCreate() {
		// 将vuex方法挂在到$u中
		// 使用方法为：如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
		// 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
		this.$u.vuex = (name, value) => {
			this.$store.commit('$uStore', {
				name,
				value
			})
		}
	},
	computed: {
		// 将vuex的state中的所有变量，解构到全局混入的mixin中
		...mapState($uStoreKey)
	},
	methods: {
		// 时间戳转换
		timestamp(timestamp) {
			if (!timestamp) {
				return ""; // 如果 timestamp 为空，则返回空字符串
			}
			const date = new Date(timestamp); // 创建一个 Date 对象，传入时间戳作为参数
			const year = date.getFullYear(); // 获取年份
			const month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份，并补零
			const day = ("0" + date.getDate()).slice(-2); // 获取日期，并补零
			const hours = ("0" + date.getHours()).slice(-2); // 获取小时，并补零
			const minutes = ("0" + date.getMinutes()).slice(-2); // 获取分钟，并补零
			const seconds = ("0" + date.getSeconds()).slice(-2); // 获取秒钟，并补零

			// 拼接成日期时间字符串
			const dateTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

			return dateTime;
		},
		// 判断企微session_key 是否有效
		qylogin() {
			const qy = uni.getStorageSync('lifeData').vuex_qy
			if (this.$u.test.isEmpty(qy)) {
				this.$u.route({
					type: 'reLaunch',
					url: '/entrydeparture/pages/login/login'
				})
				return
			}

			const that = this
			wx.qy.checkSession({
				success: function(res) {
					console.log("成功返回", res);
					//session_key 未过期，并且在本生命周期一直有效
				},
				fail: function(err) {
					// session_key 已经失效，需要重新执行登录流程
					// wx.qy.login() //重新登录
					console.log("失败返回", err);
					that.$u.route({
						type: 'reLaunch',
						url: '/entrydeparture/pages/login/login'
					})
				}
			})
		},

		// 用户信息
		userInfo() {
			this.$u.api.Member.userInfo().then(res => {
				this.$u.vuex('vuex_user', res);
			})
		},
		// 领取会员卡
		async activate() {
			const openCardData = uni.getStorageSync("openCardData")
			const vuex_user = uni.getStorageSync("lifeData").vuex_user
			this.member.code = openCardData.code
			const res = await this.$u.api.Card.activate(this.member)
			uni.showToast({
				title: "开卡成功",
				icon: 'none',
				duration: 2000 // 持续时间为 2 秒
			});
			uni.removeStorageSync("openCardData")
			this.userInfo()
		},
		// 获取用户开卡时提交的信息
		async submit(ticket) {
			const data = {
				activate_ticket: ticket
			}

			const res = await this.$u.api.Card.submit(data)
			const resList = JSON.parse(res).common_field_list
			resList.forEach(item => {
				if (item.name == "USER_FORM_INFO_FLAG_MOBILE") {
					this.member.mobile = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_SEX") {
					if (item.value == "男") {
						this.member.sex = 0
					} else if (item.value == "女") {
						this.member.sex = 1
					}
				} else if (item.name == "USER_FORM_INFO_FLAG_BIRTHDAY") {
					this.member.birthday = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_EMAIL") {
					this.member.email = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_NAME") {
					this.member.name = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_IDCARD") {
					this.member.idcard = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_EDUCATION_BACKGROUND") {
					this.member.education = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_INDUSTRY") {
					this.member.industry = item.value
				} else if (item.name == "USER_FORM_INFO_FLAG_HABIT") {
					this.member.habit = item.value
				}
			})

			const customList = JSON.parse(res).custom_field_list
			customList.forEach(item => {
				if (item.name == "车牌号") {
					this.member.plateNo = item.value
				}
			})

			const vuex_user = uni.getStorageSync("lifeData").vuex_user
			this.member.card_id = vuex_user.card_id

			this.activate()
		},
		// 开卡操作
		async open() {
			const pages = getCurrentPages(); // 获取当前页面栈的信息
			const currentPage = pages[pages.length - 1]; // 获取当前页面的信息
			const currentPagePath = currentPage.route; // 获取当前页面的地址

			const vuex_user = uni.getStorageSync("lifeData").vuex_user
			// 获取开卡插件参数
			const res = await this.$u.api.Card.open()
			const encrypt_card_id = decodeURIComponent(res.split("encrypt_card_id=")[1].split("&")[0])
			const biz = decodeURIComponent(res.split("biz=")[1])
			let extraData = {
				encrypt_card_id: encrypt_card_id,
				outer_str: '1',
				biz: biz,
				activate_type: 'ACTIVATE_TYPE_NORMAL',
				jump_appid: 'wxe64a506dc23b5ba6',
				jump_path: currentPagePath
			}
			uni.navigateToMiniProgram({
				appId: 'wxeb490c6f9b154ef9',
				extraData: extraData,
				success: function(res) {},
				fail: function() {},
				complete: function() {}
			})

		},
		// 通用方法，检测缓存用户是否登录
		hasLogin() {
			console.log('登录中,version' + this.vuex_version);
			// 版本不一致，要求重新登录
			if (this.vuex_version != '3.0.0') {
				console.log('需要清空缓存');
				this.$u.vuex('vuex_url', '');
				this.$u.vuex('vuex_user', {});
				this.$u.vuex('vuex_token', '');
				this.$u.vuex('vuex_openid', '');
			}

			console.log('登录中,vuex_token' + this.vuex_token);
			if (!this.vuex_token) {
				console.log('检测token不存在');
				this.getRoute()
				// 重置登录页
				this.$u.route({
					type: 'reLaunch',
					url: 'pages/public/web-login'
				})
			} else {
				console.log('检测token存在');
			}
		},
		// 获取当前页面路由
		getRoute() {
			let pages = getCurrentPages()
			const url = pages[pages.length - 1]['$page']['fullPath']
			// 保存当前页面路由
			console.log("打印当前页面路由::" + url);
			if (url.indexOf('login') == -1) {
				console.log("保存::" + url);
				this.$u.vuex('vuex_url', url);
			}
		},
		//解析图片地址
		getImgUrl(url) {
			if (!this.$u.test.url(url)) {
				url = url
			}
			return url
		},
		//解析文件地址
		getFileUrl(url) {
			if (!this.$u.test.url(url)) {
				url = config.domain + url
			}
			return url
		},
		//解析列表图片网络地址
		getListImgUrl(list, name) {
			list.map(val => {
				let url = val[name];
				if (!this.$u.test.url(url)) {
					val[name] = config.domain + url
				}
			})
			return list
		},
		/**
		 * 解析富文本图片地址
		 * @param {Object} content
		 */
		getHtmlImgUrl(content) {
			const that = this
			var newContent = content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function(match, capture) {
				return "<img src=" + that.getImgUrl(capture) + ' alt="" />'
			});
			return newContent
		},
		// 小程序跳转（墨博）
		toMBUrl(path) {
			uni.navigateToMiniProgram({
				appId: 'wxd7ef2badc2997089',
				path: path,
				success(res) {
					// 打开成功
				}
			})
		}
	}
}